package com.jhg.drgclinicalpathway.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.QueryChainWrapper;
import com.jhg.drgclinicalpathway.dao.*;
import com.jhg.drgclinicalpathway.domain.*;
import com.jhg.drgclinicalpathway.domain.sys.AccountInfo;
import com.jhg.drgclinicalpathway.service.ClinicalpathwaydetailService;
import com.jhg.drgclinicalpathway.service.FormWordService;
import com.jhg.drgclinicalpathway.service.LJ临床路径明细从表Service;
import io.swagger.annotations.Api;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Api("模板相关API")
@RequestMapping("tpl")
@RestController
@Slf4j(topic = "TplController")
public class TplController {


    @Autowired
    PathTplDao tplDao;

    @Autowired
    PathTplMetaDao pathTplMetaDao;

    @Autowired
    PathTplDataDao pathTplDataDao;

    @GetMapping("ls")
    public RpnMsg ls(@RequestParam(value = "s", defaultValue = "") String s,
                     @RequestParam(defaultValue = "") String status,
                     @RequestParam(defaultValue = "") String sortprop,
                     @RequestParam(defaultValue = "") String order,
                     @RequestParam(value = "page", defaultValue = "1") Integer page,
                     @RequestParam(value = "size", defaultValue = "10") Integer size) {
        QueryWrapper<PathTpl> queryWrapper = new QueryWrapper<PathTpl>();
        Page<PathTpl> pg = new Page<PathTpl>(page, size);
        if (!StringUtils.isEmpty(sortprop)) {
            if (order.equals("ascending")) {
                queryWrapper.orderByAsc(sortprop);
            } else {
                queryWrapper.orderByDesc(sortprop);
            }
        } else {
            queryWrapper.orderByDesc("最近修改日期");
        }
        //queryWrapper.orderByDesc("最近修改日期");

        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq(status, "1");
        }
        if (!StringUtils.isEmpty(s)) {
            queryWrapper.like("名称", s)
                    .or().like("疾病名称", s)
                    .or().like("分组编码", s)
                    .or().like("分组名称", s)
                    .or().like("手术名称", s);

        }

        IPage<PathTpl> patientInfoIPage = tplDao.selectPage(pg, queryWrapper);


        if (patientInfoIPage.getTotal() > 0) {
            QueryWrapper<PathTplMeta> metaQueryWrapper = new QueryWrapper<PathTplMeta>();
            metaQueryWrapper.in("模板ID", patientInfoIPage.getRecords()
                            .stream().map(it -> it.getId()).collect(Collectors.toList()))
                    .eq("备注", "适用疾病");

            List<PathTplMeta> pathTplMetas = pathTplMetaDao.selectList(metaQueryWrapper);

            for (PathTpl record : patientInfoIPage.getRecords()) {
                List<PathTplMeta> metas = pathTplMetas.stream().filter(it -> it.get模板ID().equals(record.getId())).collect(Collectors.toList());
                List<HashMap> collect = metas.stream().map(it -> new HashMap() {
                    {
                        put("疾病编码", it.get字段名称());
                        put("名称", it.get字段值());
                    }
                }).collect(Collectors.toList());
                record.set适应疾病(collect);
            }
        }


        return RpnMsg.SUCCESS(patientInfoIPage);
    }

    @GetMapping("tpl-exists")
    public RpnMsg tplExists(@RequestParam(defaultValue = "") String n) {
        QueryWrapper<PathTpl> queryWrapper = new QueryWrapper<PathTpl>();
        queryWrapper.eq("分组编码", n);
        List<PathTpl> pathTpls = tplDao.selectList(queryWrapper);
        if (pathTpls.size() > 0) {
            return RpnMsg.SUCCESS(pathTpls.get(0).getId());
        }
        return RpnMsg.SUCCESS();
    }

    /**
     * 通过模板id，获取模板相关信息
     *
     * @param id
     * @return
     */
    @GetMapping("get-tpl-id")
    public RpnMsg getTplId(String id) {
        //模板信息
        PathTpl tpl = tplDao.selectById(id);

        QueryWrapper<PathTplMeta> 模板ID = new QueryWrapper<PathTplMeta>().eq("模板ID", id);
        QueryWrapper<PathTplData> 模板ID2 = new QueryWrapper<PathTplData>().eq("模板ID", id);
        List<PathTplMeta> pathTplMetas = pathTplMetaDao.selectList(模板ID);
        List<PathTplData> data = pathTplDataDao.selectList(模板ID2);

        List<String> V临床路径项目Ids = data.stream().filter(it -> !StringUtils.isEmpty(it.getObjid())).map(it -> it.getObjid()).collect(Collectors.toList());
        if (V临床路径项目Ids.size() > 0) {
            List<V临床路径项目> v临床路径项目s = commonDao.V临床路径项目(V临床路径项目Ids);
            for (PathTplData datum : data) {
                if (!StringUtils.isEmpty(datum.getObjid())) {
                    Optional<V临床路径项目> first = v临床路径项目s.stream().filter(it -> it.getId().equals(datum.getObjid().trim())).findFirst();
                    if (first.isPresent()) {
                        datum.setXmeno(first.get().get限制说明());
                    }
                }
            }
        }


        JSONObject o = new JSONObject();
        o.put("tpl", tpl);
        o.put("metas", pathTplMetas);
        o.put("data", data);

        return RpnMsg.SUCCESS(o);
    }

    /**
     * 通过疾病获取对应的“应用于疾病编码”
     *
     * @param code
     * @return
     */
    @GetMapping("dise-path")
    public RpnMsg disePath(String code) {
        List<Map<String, Object>> maps = tplDao.selectByDisCode(code);
        return RpnMsg.SUCCESS(maps);
    }


    @Autowired
    PathTplDao pathTplDao;

    @Autowired
    ClinicalpathwaydetailDao clinicalpathwaydetailDao;

    @Autowired
    com.jhg.drgclinicalpathway.dao.LJ临床路径版本Dao LJ临床路径版本Dao;

    /**
     * 通过ID删除模板
     *
     * @param ids
     * @return
     */
    @PostMapping("del-tpls")
    public RpnMsg delTpls(String ids) {

        for (String id : ids.split(",")) {
            //删除模板本身相关信息
            pathTplDao.deleteById(id);
            QueryWrapper<PathTplData> queryWrapper = new QueryWrapper<PathTplData>();
            queryWrapper.eq("模板ID", id);

            QueryWrapper<PathTplMeta> queryWrapper1 = new QueryWrapper<PathTplMeta>();
            queryWrapper1.eq("模板ID", id);
            //删除模板相关数据
            pathTplDataDao.delete(queryWrapper);
            //删除模板元数据信息
            pathTplMetaDao.delete(queryWrapper1);

            QueryWrapper<Clinicalpathwaydetail> clinicalpathwaydetailQueryWrapper = new QueryWrapper<Clinicalpathwaydetail>();
            clinicalpathwaydetailQueryWrapper.eq("版本ID", id);
            clinicalpathwaydetailDao.delete(clinicalpathwaydetailQueryWrapper);

            QueryWrapper<LJ临床路径明细从表> lJ临床路径明细从表Query = new QueryWrapper<LJ临床路径明细从表>();
            lJ临床路径明细从表Query.eq("模板id", id);
            lj临床路径明细从表Dao.delete(lJ临床路径明细从表Query);

            LJ临床路径版本Dao.deleteById(id);

        }

        return RpnMsg.SUCCESS();
    }

    @PostMapping("copy-tpl2")
    public RpnMsg copyTpls2(@RequestBody PathTpl tpl) {
        String id = tpl.getId();


        PathTpl pathTpl = pathTplDao.selectById(tpl.getId());

        String ctime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        pathTpl.setId(UUID.randomUUID().toString());
        pathTpl.set最近修改日期(ctime);
        pathTpl.set名称(tpl.get名称());
        pathTpl.set分组编码(tpl.get分组编码());
        pathTpl.set分组名称(tpl.get分组名称());
        pathTpl.set路径ID(tpl.get路径ID());

        pathTpl.set创建日期(ctime);

        List<Map<String, Object>> maps = 临床路径模板Dao.模板ById(id);
        TplSaveVO vo = new TplSaveVO();
        vo.setTpl(pathTpl);
        List<Clinicalpathwaydetail> clinicalpathwaydetails = JSON.parseArray(JSON.toJSONString(maps), Clinicalpathwaydetail.class);
        for (Clinicalpathwaydetail l : clinicalpathwaydetails) {
            l.set版本ID(pathTpl.getId());
        }
        vo.setLs(clinicalpathwaydetails);

        return saveTpl(JSON.toJSONString(vo));
    }

//    @Autowired
//    ClinicalpathwaydetailDao clinicalpathwaydetailDao;
//
//    @Autowired
//    LJ临床路径版本Dao LJ临床路径版本Dao;

    @PostMapping("copy-tpl")
    public RpnMsg copyTpls(@RequestBody PathTpl tpl) {

        String id = tpl.getId();

        String ctime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        tpl.setId(UUID.randomUUID().toString());
        tpl.set最近修改日期(ctime);
        tpl.set创建日期(ctime);

        tplDao.insert(tpl);

        //复制模板数据
        QueryWrapper<PathTplData> queryWrapper = new QueryWrapper<PathTplData>();
        queryWrapper.eq("模板ID", id);
        List<PathTplData> data = pathTplDataDao.selectList(queryWrapper);
        for (PathTplData datum : data) {
            datum.setId(UUID.randomUUID().toString());
            datum.set模板ID(tpl.getId());
            pathTplDataDao.insert(datum);
        }
        QueryWrapper<PathTplMeta> queryWrapper1 = new QueryWrapper<PathTplMeta>();
        queryWrapper1.eq("模板ID", id);
        List<PathTplMeta> pathTplMetas = pathTplMetaDao.selectList(queryWrapper1);
        for (PathTplMeta pathTplMeta : pathTplMetas) {
            pathTplMeta.setId(UUID.randomUUID().toString());
            pathTplMeta.set模板ID(tpl.getId());
            pathTplMetaDao.insert(pathTplMeta);
        }

        QueryWrapper<Clinicalpathwaydetail> clinicalpathwaydetailQueryWrapper = new QueryWrapper<Clinicalpathwaydetail>();
        clinicalpathwaydetailQueryWrapper.eq("版本ID", id);

        List<Clinicalpathwaydetail> clinicalpathwaydetails = clinicalpathwaydetailDao.selectList(clinicalpathwaydetailQueryWrapper);

        clinicalpathwaydetails.stream().filter(it -> StringUtils.isEmpty(it.get上级ID())).forEach(it -> {
            String oid = it.getId();
            String nid = UUID.randomUUID().toString();
            it.setId(nid);
            //it.set版本ID(tpl.getId());
            clinicalpathwaydetails.stream().filter(it2 -> oid.equals(it2.get上级ID())).forEach(it2 -> {
                it2.set上级ID(nid);
                it2.setId(UUID.randomUUID().toString());
                //it2.set版本ID(tpl.getId());
            });
        });
        for (Clinicalpathwaydetail clinicalpathwaydetail : clinicalpathwaydetails) {
            clinicalpathwaydetail.set版本ID(tpl.getId());
            clinicalpathwaydetailDao.insert(clinicalpathwaydetail);
        }


        LJ临床路径版本 lj临床路径版本 = LJ临床路径版本Dao.selectById(id);
        lj临床路径版本.setId(tpl.getId());
        Map<String, KeyVal> 内外科正则 = FormWordService.内外科正则;
        for (Map.Entry<String, KeyVal> entry : 内外科正则.entrySet()) {
            if (Pattern.matches(entry.getValue().getK1().toString(), tpl.get分组编码())) {
                lj临床路径版本.set场合(entry.getKey());
                lj临床路径版本.set版本号(entry.getValue().getK2().toString());
            }
        }
        lj临床路径版本.set路径ID(Integer.valueOf(tpl.get路径ID()));
        lj临床路径版本.set病种编码(tpl.get分组编码());
        LJ临床路径版本Dao.insert(lj临床路径版本);

        return RpnMsg.SUCCESS();
    }

    @GetMapping("std-cost")
    public RpnMsg stdCost(String code) {
        return RpnMsg.SUCCESS(pathTplDao.病组标植值(code));
    }


    @GetMapping("lj-dir")
    public RpnMsg ljdir(String code) {
        Map<String, Object> 临床路径目录 = pathTplDao.临床路径目录(code);

        return RpnMsg.SUCCESS(临床路径目录);
    }

    @GetMapping("lj-version")
    public RpnMsg ljVersion(String id) {
        Map<String, Object> map = LJ临床路径版本Dao.ljInfo(id);
        return RpnMsg.SUCCESS(map);
    }

    @GetMapping("lj-check-version")
    public RpnMsg ljCheckVersion(Integer pid, Integer t) {
        List<Map<String, Object>> list = LJ临床路径版本Dao.checkLJ临床路径版本(pid, t);

        return RpnMsg.SUCCESS(list);
    }


    @Autowired
    TplFormDao formDao;

    @GetMapping("forms")
    public RpnMsg forms(@RequestParam(value = "s", defaultValue = "") String s,
                        @RequestParam(value = "page", defaultValue = "1") Integer page,
                        @RequestParam(value = "size", defaultValue = "10") Integer size) {

        QueryWrapper<TplForm> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(s)) {
            queryWrapper.like("m", s);
        }
        Page<TplForm> pg = new Page<>(page, size);

        IPage<TplForm> tplForms = formDao.selectPage(pg, queryWrapper);
        return RpnMsg.SUCCESS(tplForms);
    }


    @GetMapping("tpl-form-id")
    public RpnMsg tplFormId(String id) {
        TplForm tplForm = formDao.selectById(id);

        return RpnMsg.SUCCESS(tplForm);
    }

    @Autowired
    CommonDao commonDao;

    @GetMapping("lcljml")
    public RpnMsg lcljml() {

        List<Map<String, Object>> 临床路径目录 = commonDao.临床路径目录();

        return RpnMsg.SUCCESS(临床路径目录);
    }

    @PostMapping("tpl-form")
    public RpnMsg tplForm(@RequestBody TplForm form) {
        boolean isNew = StringUtils.isEmpty(form.getId());
        if (isNew) {
            form.setId(UUID.randomUUID().toString());

        }
        form.setCtime(new Date());

        if (isNew) formDao.insert(form);
        else formDao.updateById(form);


        return RpnMsg.SUCCESS();
    }

    @GetMapping("desotry-form")
    public RpnMsg destoryForm(String id) {
        formDao.deleteById(id);

        return RpnMsg.SUCCESS();
    }


    @GetMapping("auto-complete")
    public RpnMsg autoComplete(@RequestParam(defaultValue = "") String w, String tb) {
        List<Map<String, Object>> sql = commonDao.sql(tb, w);
        return RpnMsg.SUCCESS(sql);
    }

    @Autowired
    临床路径模板Dao 临床路径模板Dao;

    @GetMapping("tpl-detail")
    public RpnMsg tplEdit(String tplid) {
        List<Map<String, Object>> maps = 临床路径模板Dao.模板ById(tplid);
        return RpnMsg.SUCCESS(maps);
    }

    @GetMapping("tpl-detail2")
    public RpnMsg tplEdit2(String tplid) {
        List<Map<String, Object>> maps = 临床路径模板Dao.模板ById2(tplid);
        return RpnMsg.SUCCESS(maps);
    }

    @GetMapping("tpl-std")
    public RpnMsg tplStd(String tplid) {
        List<Map<String, Object>> maps = 临床路径模板Dao.模板费用(tplid);
        JSONObject o = new JSONObject();
        for (Map<String, Object> map : maps) {
            String 类别 = map.get("类别").toString();
            Object 金额 = map.getOrDefault("金额", 0);
            o.put(类别, 金额);
//            for (Map.Entry<String, Object> entry : map.entrySet()) {
//                o.put(entry.getKey(),entry.getValue());
//            }
        }
        return RpnMsg.SUCCESS(o);
    }


    @Data
    static class TplSaveVO {
        private PathTpl tpl;
        private List<Clinicalpathwaydetail> ls;
    }


    @PostMapping("save-tpl-detail")
    public RpnMsg saveTplDetail(String json) {
        List<Clinicalpathwaydetail> opLs = JSON.parseArray(json, Clinicalpathwaydetail.class);
        List<String> deleteByIdsDetails = new ArrayList<>();

        List<Clinicalpathwaydetail> insertByDetails = new ArrayList<>();
        List<LJ临床路径明细从表> insertBy从表s = new ArrayList<>();
        List<Map<String, Object>> maps = 临床路径模板Dao.模板ById(opLs.get(0).get版本ID());
        for (Clinicalpathwaydetail l : opLs) {
            try {
                String tplid = l.get版本ID();
                LJ临床路径明细从表 从表 = new LJ临床路径明细从表();
                从表.setId(l.getId());
                从表.set明细id(l.getId());
                从表.set数量(l.get数量());
                从表.set单价(l.get单价());
                从表.set金额(l.get金额());
                从表.set标杆费用(l.get标杆费用());
                从表.set模板费用(l.get模板费用());
                从表.set模板费用占比(l.get模板费用占比());
                从表.set模板分类费用(l.get模板费用());
                从表.set模板分类费用占比(l.get模板费用占比());
                从表.set模板病例数(l.get模板病例数());
                从表.set模板总费用(l.get模板费用());
                从表.set模板id(tplid);
                从表.set缺省(从表.get单价() != null && 从表.get数量() != null);
                String op = l.getOp();
                if (op.equals("insert")) {
                    //lj临床路径明细从表Dao.insert(从表);
                    insertBy从表s.add(从表);

                    OptionalInt maxOpt = maps.stream().filter(m -> m.getOrDefault("类别", "").equals(l.get类别()))
                            .mapToInt(it -> Integer.parseInt(it.getOrDefault("序号", 0).toString())).max();
                    if (maxOpt.isPresent()) {
                        l.set序号(maxOpt.getAsInt());
                    } else {
                        l.set序号(maps.size() + 1);
                    }
                    Map<String, Object> tMap = new HashMap<String, Object>() {
                        {
                            put("类别", l.get类别());
                            put("序号", l.get序号());
                        }
                    };
                    maps.add(tMap);
                    insertByDetails.add(l);
                    //clinicalpathwaydetailDao.insert(l);
                }

                if (op.equals("del")) {
                    deleteByIdsDetails.add(l.getId());
                }

                if (op.equals("update")) {
                    insertByDetails.add(l);
                    insertBy从表s.add(从表);
                }
            } catch (Exception ex) {
                log.error(ex.getMessage());
            }
        }

        if (deleteByIdsDetails.size() > 0) {
            lj临床路径明细从表Dao.deleteBatchIds(deleteByIdsDetails);
            clinicalpathwaydetailDao.deleteBatchIds(deleteByIdsDetails);
        }

        if (insertByDetails.size() > 0) clinicalpathwaydetailService.saveOrUpdateBatch(insertByDetails);
        if (insertBy从表s.size() > 0) lj临床路径明细从表Service.saveOrUpdateBatch(insertBy从表s);

        return RpnMsg.SUCCESS();
    }

    @Autowired
    LJ临床路径明细从表Dao lj临床路径明细从表Dao;

    @Autowired
    ClinicalpathwaydetailService clinicalpathwaydetailService;

    @Autowired
    LJ临床路径明细从表Service lj临床路径明细从表Service;

    @PostMapping("save-tpl")
    public RpnMsg saveTpl(String json) {
        TplSaveVO vo = JSON.parseObject(json, TplSaveVO.class);
        List<Clinicalpathwaydetail> ls = vo.getLs();
        ls.sort((a, b) -> a.get序号().compareTo(b.get序号()));

        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        PathTpl tpl = vo.getTpl();
        tpl.set最近修改日期(dft.format(new Date()));
        if (pathTplDao.updateById(tpl) == 0) {
            pathTplDao.insert(tpl);
        }

        List<String> ids = ls.stream().map(it -> it.get项目id()).distinct().collect(Collectors.toList());
//        List<V临床路径项目> v临床路径项目s = 临床路径模板Dao.获取小分类ID(ids);
//        Map<String,String> 项目小分类Map=new HashMap<>();

        String tplid = tpl.getId();
        if (ls.size() > 0) {
            tplid = ls.get(0).get版本ID();
        }
        QueryWrapper<Clinicalpathwaydetail> clinicalpathwaydetailQueryWrapper = new QueryWrapper<Clinicalpathwaydetail>();
        clinicalpathwaydetailQueryWrapper.eq("版本ID", tplid);

        clinicalpathwaydetailDao.delete(clinicalpathwaydetailQueryWrapper);

        List<String> 项目IDS = ls.stream().map(it -> it.get项目id()).distinct().collect(Collectors.toList());
        List<V临床路径项目> 通过名称获取项目编码 = commonDao.通过项目ID获取项目编码(项目IDS);


        Func2<String, String> 获取上级编码 = (项目id) -> {
            List<V临床路径项目> ts = 通过名称获取项目编码.stream().filter(it -> it.getId().equals(项目id)).collect(Collectors.toList());
            if (ts.size() > 0) {
                return ts.get(0).get上级ID();
            }
            return "";
        };
//        for (V临床路径项目 v : v临床路径项目s) {
//            项目小分类Map.put(v.getId(),v.get上级ID());
//        }

        QueryWrapper<LJ临床路径明细从表> lJ临床路径明细从表Query = new QueryWrapper<LJ临床路径明细从表>();
        lJ临床路径明细从表Query.eq("模板id", tplid);
        lj临床路径明细从表Dao.delete(lJ临床路径明细从表Query);

        List<String> 从表Ids = ls.stream().filter(it -> !StringUtils.isEmpty(it.get从表ID()))
                .map(it -> it.get从表ID()).collect(Collectors.toList());
        if (从表Ids.size() > 0) {
            lj临床路径明细从表Dao.deleteBatchIds(从表Ids);
        }

        List<Clinicalpathwaydetail> clinicalpathwaydetails = new ArrayList<>();

        List<LJ临床路径明细从表> 从表s = new ArrayList<>();

        String finalTplid = tplid;
        Action1<Clinicalpathwaydetail> thunk = (l) -> {

            String 项目id = l.get项目id();

            //看有无上级ID

            //l.set上级ID(orDefault)

            l.set版本ID(finalTplid);
            //l.setId(UUID.randomUUID().toString());
            double 总金额 = ls.stream().filter(it -> it.get金额() != null).mapToDouble(it -> it.get金额()).sum();

            LJ临床路径明细从表 从表 = new LJ临床路径明细从表();
            从表.setId(l.getId());
            从表.set明细id(l.getId());
            从表.set数量(l.get数量());
            从表.set单价(l.get单价());
            从表.set金额(l.get金额());
            从表.set标杆费用(l.get标杆费用());
            从表.set模板费用(l.get模板费用());
            从表.set模板费用占比(l.get模板费用占比());
            从表.set模板分类费用(l.get模板费用());
            从表.set模板分类费用占比(l.get模板费用占比());
            从表.set模板病例数(l.get模板病例数());
            从表.set模板总费用(总金额);
            从表.set模板id(finalTplid);
            从表.set缺省(从表.get单价() != null && 从表.get数量() != null);
            从表s.add(从表);
            //lj临床路径明细从表Dao.insert(从表);
            //clinicalpathwaydetailDao.insert(l);
            // clinicalpathwaydetails.add(l);
            clinicalpathwaydetails.add(l);

        };
        for (Clinicalpathwaydetail l : ls) {
            try {
                String 项目id = l.get项目id();
                l.setId(UUID.randomUUID().toString());
                String s = 获取上级编码.get(项目id);
                if (!StringUtils.isEmpty(s)) {
                    Optional<Clinicalpathwaydetail> first = ls.stream().filter((it) -> it.get项目id().equals(s)).findFirst();
                    Optional<Clinicalpathwaydetail> second = clinicalpathwaydetails.stream().filter((it) -> it.get项目id().equals(s)).findFirst();
                    if (!first.isPresent() && !second.isPresent()) {
                        //复制一份当前数据，插入上级项目
                        Clinicalpathwaydetail copyObj = JSON.parseObject(JSON.toJSONString(l), Clinicalpathwaydetail.class);
                        copyObj.setId(UUID.randomUUID().toString());
                        copyObj.set项目id(s);
                        copyObj.set名称(null);
                        copyObj.set上级ID(null);
                        copyObj.set组号(null);
                        copyObj.set序号(-10);
                        l.set上级ID(copyObj.getId());
                        thunk.accept(copyObj);
                    } else {
                        String sid = first.isPresent() ? first.get().getId() : second.get().getId();
                        l.set上级ID(sid);
                    }
                }
                thunk.accept(l);
            } catch (Exception ex) {
            }
        }
        for (int i = 0; i < clinicalpathwaydetails.size(); i++) {
            Clinicalpathwaydetail l = clinicalpathwaydetails.get(i);
            l.set序号(i + 1);
//            clinicalpathwaydetailDao.insert(l);
        }
        lj临床路径明细从表Service.saveBatch(从表s);
        clinicalpathwaydetailService.saveBatch(clinicalpathwaydetails);


        //1.通过疾病编码获取路径ID
        Integer wayid = 0;
        if (!StringUtils.isEmpty(tpl.get路径ID())) {
            wayid = Integer.parseInt(tpl.get路径ID());
        }


        LJ临床路径版本 lj临床路径版本 = new LJ临床路径版本();
        lj临床路径版本.setId(tpl.getId());
        lj临床路径版本.set创建时间(new Date());
        lj临床路径版本.set标准床日(0);
        lj临床路径版本.set标准金额(0.0);
        lj临床路径版本.set版本号(tpl.get路径版本());
        lj临床路径版本.set版本说明("");
        lj临床路径版本.set状态(0);
        lj临床路径版本.set路径ID(wayid);
        lj临床路径版本.set创建人("管理员");

        if (!StringUtils.isEmpty(tpl.get路径版本())) {
            //lj临床路径版本.set病种编码(tpl.get分组编码());
            lj临床路径版本.set场合(tpl.get路径版本().split("-")[0]);
        }

        QueryWrapper<LJ临床路径版本> lj临床路径版本QueryWrapper = new QueryWrapper<LJ临床路径版本>();
        lj临床路径版本QueryWrapper.eq("路径ID", tpl.get路径ID());
        lj临床路径版本QueryWrapper.eq("版本号", tpl.get路径版本());
        lj临床路径版本QueryWrapper.eq("场合", lj临床路径版本.get场合());
        LJ临床路径版本 old临床路径版本 = LJ临床路径版本Dao.selectById(tpl.getId());
        if (old临床路径版本 == null) {
            LJ临床路径版本Dao.insert(lj临床路径版本);
        }


        return RpnMsg.SUCCESS();
    }

    @GetMapping("drg-names")
    public RpnMsg drgNames(String wid) {
        List<Map<String, String>> maps = 临床路径模板Dao.获取分组by路径ID(wid);
        return RpnMsg.SUCCESS(maps);
    }

    @GetMapping("drg-info")
    public RpnMsg drgInfo(String code) {
        List<Map<String, String>> maps = 临床路径模板Dao.标杆值信息by分组编码(code);
        return RpnMsg.SUCCESS(maps);
    }

    @GetMapping("drg-info2")
    public RpnMsg drgInfo2(String code) {
        QueryWrapper<V病组标杆维护> queryWrapper = new QueryWrapper<V病组标杆维护>();
        queryWrapper.eq("分组编码", code);

        List<Map<String, String>> maps = 临床路径模板Dao.标杆值信息by分组编码(code);
        return RpnMsg.SUCCESS(maps);
    }

    @PostMapping("cp-tpl")
    public RpnMsg cpTpl(String tplid, Integer pid, String ch, String doc) {
        try {
            临床路径模板Dao.PRO_LJ_路径明细复制(tplid, pid, ch, doc);
        } catch (Exception ex) {
            return RpnMsg.FAIL(ex.getMessage());
        }
        return RpnMsg.SUCCESS();
    }

    @GetMapping("cn-hops")
    public RpnMsg cnHops() {
        return RpnMsg.SUCCESS(commonDao.中医院性质());
    }

    @Autowired
    V病组标杆维护Dao v病组标杆维护Dao;
    @Autowired
    JC路径指标参考Dao jc路径指标参考Dao;

    @PostMapping("save-tpl-drg")
    public RpnMsg saveTplDrg(@RequestBody JC路径指标参考 d) {
        jc路径指标参考Dao.updateById(d);
        return RpnMsg.SUCCESS();
    }

    @GetMapping("drg-weight-byid")
    public RpnMsg drgweightbyid(String wid, String code, @RequestParam(defaultValue = "") String source) {
        QueryWrapper<V病组标杆维护> queryWrapper = new QueryWrapper<V病组标杆维护>();
        queryWrapper.eq("路径ID", wid).eq("分组编码", code);
        if (!StringUtils.isEmpty(source)) {
            queryWrapper.eq("来源", source);
        }
        List<V病组标杆维护> v病组标杆维护s = v病组标杆维护Dao.selectList(queryWrapper);
        if (v病组标杆维护s.size() > 1) {
            return RpnMsg.SUCCESS(v病组标杆维护s);
        }
        if (v病组标杆维护s.size() > 0) {
            return RpnMsg.SUCCESS(v病组标杆维护s.get(0));
        }

        return RpnMsg.SUCCESS();
    }


    @GetMapping("drg-weight-ls")
    public RpnMsg drgWeightLs(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(defaultValue = "") String s
    ) {
        Page<V病组标杆维护> pageInfo = new Page<V病组标杆维护>(page, size);

        QueryWrapper<V病组标杆维护> queryWrapper = new QueryWrapper<V病组标杆维护>();
        if (!StringUtils.isEmpty(s)) {
            queryWrapper.like("分组编码", s).or().like("路径名称", s);
        }
        //System.out.println("操作："+filterType);
        //queryWrapper.eq("来源",1).eq("路径名称","肺部感染");
        queryWrapper.orderByAsc("路径id").orderByAsc("分组编码").orderByAsc("来源");
        IPage<V病组标杆维护> ls = v病组标杆维护Dao.selectPage(pageInfo, queryWrapper);
        return RpnMsg.SUCCESS(ls);
    }

    @Autowired
    YbMsgDao ybdao;

    @PostMapping("save-msg")
    public RpnMsg saveTplMsg(@RequestBody Map<String, Object> map) {
        String msg = map.get("msg").toString();
        String jzh = map.get("jzh").toString();
        String fsr = map.get("fsr").toString();
        String jsr = map.get("jsr").toString();
        List<Map<String, Object>> map3 = ybdao.getMsgByfsr(fsr, jzh);
        if (map3.size() > 0) {
            YB_MSG ym = new YB_MSG();
            ym.setId(Integer.parseInt(map3.get(0).get("id").toString()));
            ym.setMsg(msg);
            ym.setMsg(msg);
            ym.setSend(fsr);
            ym.setAnser(jsr);
            return RpnMsg.SUCCESS(ybdao.updateById(ym));
        } else {
            YB_MSG ym = new YB_MSG();
            ym.setZt(0);
            ym.setCjsj(new Date());
            ym.setJzh(jzh);
            ym.setMsg(msg);
            ym.setSend(fsr);
            ym.setAnser(jsr);
            return RpnMsg.SUCCESS(ybdao.insert(ym));
        }
    }

    @PostMapping("get-msg")
    public RpnMsg getMsgByjsr(@RequestBody Map<String, Object> map) {
        String fsr = map.get("fsr").toString();
        String jzh = map.get("jzh").toString();
        String jsr = map.get("jsr").toString();
        String zt = map.get("zt").toString();

        if ("".equals(fsr) && "0".equals(zt)) {
            // 根据状态查询
            List<Map<String, Object>> map2 = ybdao.getMsgByjsrZt(jsr, zt);
            return RpnMsg.SUCCESS(map2);
        } else if ("".equals(fsr)) {
            // 根据接收人获取消息
            List<Map<String, Object>> map1 = ybdao.getMsgByjsr(jsr);
            return RpnMsg.SUCCESS(map1);
        } else if (!"".equals(fsr) && "".equals(jzh)) {
            QueryWrapper<YB_MSG> queryWrapper = new QueryWrapper<YB_MSG>();
            queryWrapper.eq("send", fsr);
            List<YB_MSG> maps = ybdao.selectList(queryWrapper);
            return RpnMsg.SUCCESS(maps);
        } else {
            // 根据发送人获取消息
            List<Map<String, Object>> map3 = ybdao.getMsgByfsr(fsr, jzh);
            return RpnMsg.SUCCESS(map3);
        }
    }

    @PostMapping("up-msg")
    public RpnMsg updateMessage(@RequestBody Map<String, Object> map) {
        int id = (int) map.get("id");
        String msg = map.get("msg").toString();
        YB_MSG ym = new YB_MSG();
        ym.setId(id);
        if ("".equals(msg)) {
            String rmsg = map.get("rmsg").toString();
            String jsr = map.get("jsr").toString();
            ym.setRmsg(rmsg);
            ym.setAnser(jsr);
            ym.setZt(2);
            ym.setRssj(new Date());
        } else {
            ym.setMsg(msg);
        }
        return RpnMsg.SUCCESS(ybdao.updateById(ym));
    }

    public PathTplDao getTplDao() {
        return tplDao;
    }


    /***
     * 路径异常明细
     * @param map
     * @return
     */
    @PostMapping("PgjgDetial")
    public RpnMsg PathPgDetial(@RequestBody Map<String, Object> map) {
        int tp = (int) map.get("tp");
        String param = map.get("param").toString();
        if (tp == 1) {
            // 主要诊断依据不足
            return RpnMsg.SUCCESS(pathTplDao.pathDetailByBrid1(param));
        } else if (tp == 2) {
            // 次要诊断依据不足w
            return RpnMsg.SUCCESS(pathTplDao.pathDetailByBrid2(param));
        } else if (tp == 3) {
            // 违反核心治疗
            return RpnMsg.SUCCESS(pathTplDao.pathDetailByBrid3(param));
        } else if (tp == 4) {
            // 疑似主要诊断与手术不匹配
            return RpnMsg.SUCCESS(pathTplDao.pathDetailByBrid4(param));
        } else if (tp == 5) {
            //  疑似入组错误
            return RpnMsg.SUCCESS(pathTplDao.pathDetailByBrid5(param));
        }
        return RpnMsg.FAIL("参数错误");
    }
}
